<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Permission;
use app\model\RolePermission;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 权限控制器
 * Class PermissionController
 * @package app\controller
 */
class PermissionController extends BaseController
{
    /**
     * 权限列表
     * @return \think\response\Json
     */
    public function index()
    {
        try {
            $keyword = $this->request->param('keyword', '');
            $type = $this->request->param('type', '');
            $status = $this->request->param('status', '');

            $where = [];
            if (!empty($keyword)) {
                $where[] = ['name|code', 'like', '%' . $keyword . '%'];
            }
            if (!empty($type)) {
                $where[] = ['type', '=', $type];
            }
            if ($status !== '') {
                $where[] = ['status', '=', $status];
            }

            $list = Permission::getTree($where);

            return $this->success($list);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取所有权限（树形结构）
     * @return \think\response\Json
     */
    public function tree()
    {
        try {
            $tree = Permission::getTree(['status' => 1]);
            return $this->success($tree);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 权限详情
     * @param int $id
     * @return \think\response\Json
     */
    public function read(int $id)
    {
        try {
            $permission = Permission::find($id);
            if (!$permission) {
                return $this->error('权限不存在');
            }

            return $this->success($permission);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 创建权限
     * @return \think\response\Json
     */
    public function save()
    {
        try {
            $data = $this->request->post();
            
            // 验证数据
            $this->validate($data, [
                'name' => 'require|length:2,50',
                'code' => 'require|length:2,100|unique:permissions',
                'type' => 'require|in:menu,button,api',
                'parent_id' => 'integer',
                'path' => 'length:0,255',
                'component' => 'length:0,255',
                'icon' => 'length:0,50',
                'sort' => 'integer',
                'status' => 'in:0,1'
            ], [
                'name.require' => '权限名称不能为空',
                'name.length' => '权限名称长度为2-50位',
                'code.require' => '权限代码不能为空',
                'code.length' => '权限代码长度为2-100位',
                'code.unique' => '权限代码已存在',
                'type.require' => '权限类型不能为空',
                'type.in' => '权限类型不正确',
                'parent_id.integer' => '父级权限ID必须是整数',
                'path.length' => '路由路径长度不能超过255位',
                'component.length' => '组件路径长度不能超过255位',
                'icon.length' => '图标长度不能超过50位',
                'sort.integer' => '排序必须是整数',
                'status.in' => '状态值不正确'
            ]);

            // 验证父级权限
            if (!empty($data['parent_id'])) {
                $parent = Permission::find($data['parent_id']);
                if (!$parent) {
                    return $this->error('父级权限不存在');
                }
            }

            $permission = Permission::create([
                'name' => $data['name'],
                'code' => $data['code'],
                'type' => $data['type'],
                'parent_id' => $data['parent_id'] ?? 0,
                'path' => $data['path'] ?? '',
                'component' => $data['component'] ?? '',
                'icon' => $data['icon'] ?? '',
                'sort' => $data['sort'] ?? 0,
                'status' => $data['status'] ?? 1
            ]);

            return $this->success($permission, '创建成功');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 更新权限
     * @param int $id
     * @return \think\response\Json
     */
    public function update(int $id)
    {
        try {
            $permission = Permission::find($id);
            if (!$permission) {
                return $this->error('权限不存在');
            }

            $data = $this->request->put();
            
            // 验证数据
            $this->validate($data, [
                'name' => 'require|length:2,50',
                'code' => 'require|length:2,100|unique:permissions,code,' . $id,
                'type' => 'require|in:menu,button,api',
                'parent_id' => 'integer',
                'path' => 'length:0,255',
                'component' => 'length:0,255',
                'icon' => 'length:0,50',
                'sort' => 'integer',
                'status' => 'in:0,1'
            ], [
                'name.require' => '权限名称不能为空',
                'name.length' => '权限名称长度为2-50位',
                'code.require' => '权限代码不能为空',
                'code.length' => '权限代码长度为2-100位',
                'code.unique' => '权限代码已存在',
                'type.require' => '权限类型不能为空',
                'type.in' => '权限类型不正确',
                'parent_id.integer' => '父级权限ID必须是整数',
                'path.length' => '路由路径长度不能超过255位',
                'component.length' => '组件路径长度不能超过255位',
                'icon.length' => '图标长度不能超过50位',
                'sort.integer' => '排序必须是整数',
                'status.in' => '状态值不正确'
            ]);

            // 验证父级权限
            if (!empty($data['parent_id'])) {
                if ($data['parent_id'] == $id) {
                    return $this->error('不能选择自己作为父级权限');
                }
                
                $parent = Permission::find($data['parent_id']);
                if (!$parent) {
                    return $this->error('父级权限不存在');
                }
                
                // 检查是否会形成循环
                $childrenIds = Permission::getChildrenIds($id);
                if (in_array($data['parent_id'], $childrenIds)) {
                    return $this->error('不能选择自己的子级权限作为父级权限');
                }
            }

            $permission->save([
                'name' => $data['name'],
                'code' => $data['code'],
                'type' => $data['type'],
                'parent_id' => $data['parent_id'] ?? 0,
                'path' => $data['path'] ?? '',
                'component' => $data['component'] ?? '',
                'icon' => $data['icon'] ?? '',
                'sort' => $data['sort'] ?? 0,
                'status' => $data['status'] ?? 1
            ]);

            return $this->success($permission, '更新成功');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除权限
     * @param int $id
     * @return \think\response\Json
     */
    public function delete(int $id)
    {
        try {
            $permission = Permission::find($id);
            if (!$permission) {
                return $this->error('权限不存在');
            }

            // 检查是否有子级权限
            $childrenCount = Permission::where('parent_id', $id)->count();
            if ($childrenCount > 0) {
                return $this->error('该权限下还有子级权限，不能删除');
            }

            // 检查是否有角色使用该权限
            $roleCount = RolePermission::where('permission_id', $id)->count();
            if ($roleCount > 0) {
                return $this->error('该权限已被角色使用，不能删除');
            }

            $permission->delete();

            return $this->success([], '删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 批量删除权限
     * @return \think\response\Json
     */
    public function batchDelete()
    {
        try {
            $ids = $this->request->post('ids', []);
            if (empty($ids) || !is_array($ids)) {
                return $this->error('请选择要删除的权限');
            }

            // 检查是否有子级权限
            $childrenCount = Permission::whereIn('parent_id', $ids)->count();
            if ($childrenCount > 0) {
                return $this->error('选中的权限下还有子级权限，不能删除');
            }

            // 检查是否有角色使用这些权限
            $roleCount = RolePermission::whereIn('permission_id', $ids)->count();
            if ($roleCount > 0) {
                return $this->error('选中的权限已被角色使用，不能删除');
            }

            Permission::whereIn('id', $ids)->delete();

            return $this->success([], '批量删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 修改状态
     * @param int $id
     * @return \think\response\Json
     */
    public function changeStatus(int $id)
    {
        try {
            $permission = Permission::find($id);
            if (!$permission) {
                return $this->error('权限不存在');
            }

            $status = $this->request->post('status');
            if (!in_array($status, [0, 1])) {
                return $this->error('状态值不正确');
            }

            $permission->status = $status;
            $permission->save();

            return $this->success([], '状态修改成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}